package middol.utils

import grails.gorm.transactions.Transactional
import groovy.transform.CompileStatic
import middol.config.UploadCfg
import middol.upload.IFileInfo
import middol.upload.IUploadHandler
import middol.upload.LocalFileInfo
import middol.upload.UploadHandlerContext
import middol.upload.UploadHandlerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.multipart.MultipartFile

import java.text.SimpleDateFormat

/**
* @Description:    上传操作
* @Author:         zhangjiayu@middol.com
* @CreateDate:     2020/10/22 11:20
* @Version:        1.0
*/
@CompileStatic
class UploadService {
    @Autowired
    UploadHandlerContext uploadHandlerContext

    @Autowired
    UploadCfg uploadCfg

    /**
     * 上传文件
     * @param fileInfo
     */
    def upload(IFileInfo fileInfo) {
        IUploadHandler uploadHandler = UploadHandlerFactory.getUploadHandler(uploadCfg.type)
        uploadHandlerContext.setiUploadHandler(uploadHandler)
        uploadHandlerContext.handleUpload(fileInfo)
    }

    /**
     * 创建本地文件上传文件信息
     * @param file
     * @param dirPath
     * @return
     */
    IFileInfo createLoaclFileInfo(MultipartFile file, String dirPath){
        IFileInfo fileInfo = new LocalFileInfo()
        fileInfo.rootDir = uploadCfg.rootDir
        String fileName = file.getOriginalFilename()     // 获取文件名称
        if (fileName != null && fileName != '') {
            fileInfo.fileType = fileName[fileName.indexOf(".")..fileName.length() - 1]  // 获取文件类型
        }
        fileInfo.dirPath = dirPath?.replace('\\', '/')
        fileInfo.newFileName = fileName.substring(0, fileName.indexOf('.')) + "_" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + fileInfo.fileType
        return fileInfo
    }

}
